/// File: install-package\program.fs
/// 
/// Author: Antonio Cisternino (cisterni@di.unipi.it)
///   
/// ------------------------------------------------------------
/// Copyright (c) Microsoft Corporation.  All rights reserved.
/// 
/// The use and distribution terms for this software are 
/// contained in the file named license.txt, which can be found 
/// in the root of this distribution.
/// By using this software in any fashion, you are agreeing to 
/// be bound by the terms of this license.
///
/// You must not remove this notice, or any other, from this
/// software.
/// ------------------------------------------------------------

open System
open System.IO

open VSLab.Packages
open System.Windows.Forms

let args = Environment.GetCommandLineArgs()

let error (s:string) =
  MessageBox.Show ((sprintf "%s\n\nUsage: install-package [-remove] [-user|-global] <package dll>" s), "VSLab package installer", MessageBoxButtons.OK, MessageBoxIcon.Warning) |> ignore
  exit(1)  

if args.Length < 2 || args.Length > 4 then
  error("Invalid number of arguments.\n")

let mutable remove = false
let mutable user = true

let sfn = args.[args.Length - 1]

if args.Length > 2 then
  for i=1 to (args.Length - 2) do
    match args.[i] with
    | "-user" -> user <- true
    | "-global" -> user <- false
    | "-remove" -> remove <- true
    | v -> error (sprintf "Invalid switch %s" v)  

if not remove && not(CheckPackage(sfn)) then
  error "Invalid package."

let fn = (if user then UserPackageDir else GlobalPackageDir) + (new FileInfo(sfn)).Name

try
  if remove then
    if not(File.Exists(fn)) then
      error "Package not present in cache!"
    File.Delete(fn)
  else
    File.Copy(sfn, fn, true)
with
| _ -> error "Operation failed"

exit(0)
